package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * projectName: com.atguigu.tingshu.account.receiver
 *
 * @author: 吴振鹏
 * description:
 * time: 2025/9/2 15:29
 */
@Component
@Slf4j
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private RechargeInfoService rechargeInfoService;

    /**
     * 充值成功
     * @param orderNo
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_RECHARGE_PAY_SUCCESS,durable = "true",autoDelete="false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER),
            key = MqConst.ROUTING_RECHARGE_PAY_SUCCESS
    ))
    public void rechargePaySuccess(String orderNo, Message message, Channel channel){
        System.out.println("充值成功，订单号："+orderNo);
        //  判断
        if (!StringUtils.isEmpty(orderNo)){
            //  修改订单状态;
            rechargeInfoService.updateRechargeInfo(orderNo);
        }
        //  收到确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    /**
     * 用户注册成功，发送消息，创建用户账户
     *
     * @param userId
     * durable 持久化 true
     * autoDelete 删除队列 false 不自动删除
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void userRegister(Long userId, Message message, Channel channel) {
        System.out.println("用户注册成功，用户id：" + userId);
        try {
            if(null!=userId){
                //说明获取了用户id,调用服务层方法  在此需要给当前注册的用户进行初始化充值;  同步：异步：mq 发送消息;
                userAccountService.userRegister(userId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }

        //  手动确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
